﻿using Microsoft.EntityFrameworkCore;
using ZH.GPT.Infrastructures.Enum;
using ZH.GPT.Infrastructures.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZH.GPT.Infrastructures.Repositories.Interface;

namespace ZH.GPT.Infrastructures.Repositories
{
    /// <summary>
    /// 基础Service
    /// </summary>
    public class BaseRepository 
    {
        /// <summary>
        /// DbContextFactory
        /// </summary>
        protected IDbContextFactory dbContextFactory = null;

        /// <summary>
        /// _DbContext
        /// </summary>
        protected MainDBContext dbContext { get; set; }

        /// <summary>
        /// 基础Service构造函数
        /// </summary>
        /// <param name="dbContextFactory"></param>
        public BaseRepository(IDbContextFactory dbContextFactory)
        {
            this.dbContextFactory = dbContextFactory;
        }

        /// <summary>
        /// Find
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="dbOption"></param>
        /// <returns></returns>
        public async Task<T> FindAsync<T>(Guid id, DBOption dbOption = DBOption.Slave) where T : class
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(dbOption);
            return await dbContext.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">当前对象</param>
        /// <returns></returns>
        public async Task<bool> AddAsync<T>(T t) where T : class
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Master);
            dbContext.Set<T>().Add(t);
            return (await CommitAsync() == 1);
        }

        /// <summary>
        /// 添加的批量操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<int> AddBatchAsync<T>(List<T> list) where T : class
        {
            dbContext = (MainDBContext)dbContextFactory.GetDbContext(DBOption.Master);
            foreach (T item in list)
                dbContext.Set<T>().Add(item);
            return await this.CommitAsync();
        }

        /// <summary>
        /// 提交
        /// </summary>
        public async Task<int> CommitAsync()
        {
            return await this.dbContext.SaveChangesAsync();
        }
    }
}
